/**
 * Created by sicongdu on 17-11-3.
 */
var mongoose = require('mongoose');

const express = require('express');
const qs = require('querystring');
const crypto = require('crypto');
const request = require('request');
const fs = require('fs');

var Promise = require('bluebird');

import config from './config';

var helloworld = express.Router();

var user = require('./user_model').helloworld_users;
var groups = require('./user_model').groups;

var isValid = 0;

const parseString = require('xml2js').parseString; //引入xml2js包

var token = '';

var error = {
  error_no: 2,
  error_msg: '内部错误，请联系杜思聪～'
};

const getAccessToken = function () {
  let queryParams = {
    grant_type: 'client_credential',
    appid: config.appId,
    secret: config.appSecret
  };

  let wxGetAccessTokenBaseUrl =
    'https://api.weixin.qq.com/cgi-bin/token?' + qs.stringify(queryParams);
  let options = {
    method: 'GET',
    url: wxGetAccessTokenBaseUrl
  };
  return new Promise((resolve, reject) => {
    request(options, function (err, res, body) {
      if (res) {
        resolve(JSON.parse(body));
      } else {
        getAccessToken()
      }
    });
  });
};

//保存与更新
const saveToken = function () {
  getAccessToken().then(function (res) {
    token = res['access_token'];
    console.log('token:  ' + token);
  });
};

const refreshToken = function () {
  saveToken();
  setInterval(function () {
    saveToken();
  }, 7000 * 1000);
  isValid = 1;
};

if (!isValid) {
  refreshToken();
  console.log("access_token已保存");
}

helloworld.use('/message', function (req, res, next) {
  var buffer = [];
  //监听 data 事件 用于接收数据
  req.on('data', function (data) {
    buffer.push(data);
  });
  //监听 end 事件 用于处理接收完成的数据
  req.on('end', function () {
    var msgXml = Buffer.concat(buffer).toString('utf-8');
    //解析xml, xml2js默认会把子子节点的值变为一个数组, explicitArray设置为false
    parseString(msgXml, { explicitArray: false }, function (err, result) {
      if (!err) {
        //打印解析结果
        console.log(result);

        if (result.xml.MsgType == 'event') {
          //判断事件类型
          switch (result.xml.Event.toLowerCase()) {
            case 'subscribe':
              //回复消息
              subscribe(req, res, result);
              break;
            case 'unsubscribe':
              //回复消息
              unsubscribe(req, res, result);
              break;
            case 'TEMPLATESENDJOBFINISH'.toLowerCase():
              //回复消息
              templateFinish(req, res, result);
              break;
            default:
              break;
          }
        } else if (result.xml.MsgType == 'text') {
          feed_back(req, res, result);
        }

      } else {
        //打印错误信息
        console.log(err);
        res.send('');
      }
    });
  });

  // var signature = req.query.signature
  // var timestamp = req.query.timestamp
  // var nonce = req.query.nonce
  // var echostr = req.query.echostr
  // var token = config.token

  // var reqArray = [nonce, timestamp, token];

  // //对数组进行字典排序
  // reqArray.sort();
  // var sortStr = reqArray.join('');//连接数组
  // var sha1Str = sha1(sortStr);

  // if (signature === sha1Str) {
  //   res.end(echostr);
  // } else {
  //   res.end("false");
  //   console.log("授权失败!");
  // }
});

var getOpenId = require('../login/getOpenId').getOpenId;
var records = require('./user_model').records;
helloworld.post('/add', (req, res, next) => {
  var code = req.body.code;
  var content = req.body.content;
  var step = req.body.step || -1
  var stepAnswer = req.body.stepAnswer || ""
  var stepResult = req.body.result || ""
  console.log(code, content);

  var add = info => {
    console.log('用户信息：', info.openid, info.unionid);
    records.create(
      {
        openID: info.openid,
        unionID: info.unionid,
        content: content,
        step: step,
        stepAnswer,
        stepResult
      },
      (err, doc) => {
        if (err) {
          res.send(error);
        } else {
          res.send({
            error_no: 1,
            error_msg: 'ok'
          });
        }
      }
    );
  };

  getOpenId(code, add, res, {}, 3);
});

helloworld.post('/delete', (req, res, next) => {
  var code = req.body.code;
  var _id_temp = req.body._id;
  console.log(code, _id_temp);

  records.remove(
    {
      _id: _id_temp
    },
    (err, doc) => {
      if (err) {
        res.send(error);
      } else {
        res.send({
          error_no: 1,
          error_msg: 'ok'
        });
      }
    }
  );
});

helloworld.post('/query', (req, res, next) => {
  var code = req.body.code;
  console.log(code);

  var query = info => {
    console.log('用户信息：', info.openid, info.unionid);
    records
      .find({
        openID: info.openid,
        //unionID: info.unionid
      })
      .sort({ _id: 1 })
      .exec((err, docs) => {
        if (err) {
          res.send(error);
        } else {
          var days = 0

          if (docs[0]) {
            var date = new Date(Number(parseInt(docs[0]._id.toString().substr(0, 8), 16).toString() + '000'))
            var now = new Date()
            days = 1 + parseInt((now - date) / (1000 * 3600 * 24))
          }

          res.send({
            error_no: 1,
            error_msg: 'ok',
            records: docs,
            days
          });
        }
      });
  };

  getOpenId(code, query, res, {}, 3);
});

//检查是否关注公众号
helloworld.post('/checkSubscription', (req, res, next) => {
  var code = req.body.code;
  console.log(code);

  var query = info => {
    console.log('用户信息：', info.openid, info.unionid);
    user
      .findOne({
        "$or": [{ openID: info.openid }, { unionID: info.unionid }]
      })
      .exec((err, doc) => {
        if (err) {
          res.send(error);
        } else {

          res.send({
            error_no: 1,
            error_msg: 'ok',
            doc
          });
        }
      });
  };

  getOpenId(code, query, res, {}, 3);
});

//查询群组列表
helloworld.post('/groupIn', (req, res, next) => {
  var code = req.body.code;
  var num = req.body.num
  console.log(code);

  var query = info => {
    console.log('用户信息：', info.openid, info.unionid);
    var seg = ""
    if (num == 1) seg = "groups"
    else if (num == 2) seg = "C_groups"
    user
      .findOne({
        "$or": [{ openID: info.openid }, { unionID: info.unionid }]
      }, { [seg]: 1, _id: 0 }, (err, docs) => {
        if (err) {
          res.send(error);
        } else {
          res.send({
            error_no: 1,
            error_msg: 'ok',
            groups: docs
          });
        }
      });
  };

  getOpenId(code, query, res, {}, 3);
});

//加入群组
helloworld.post('/join', (req, res, next) => {
  var code = req.body.code;
  var _id = req.body._id
  var name = req.body.name

  var addToGroup = info => {
    console.log('用户信息：', info.openid, info.unionid);

    //群组信息更新
    var updateGroup = () => {
      return new Promise(function (resolve, reject) {
        groups
          .updateOne({ _id }, {
            $push: {
              members: {
                openID: info.openid,
                XXopenID: "",
                unionID: info.unionid,
                name: "",
              }
            }
          }, (err, doc) => {
            if (err) {
              res.send(error);
            } else {
              resolve()
            }
          })
      })

    }

    // //查询user是否注册
    // var check = () => {
    //   return new Promise(function (resolve, reject) {
    //     user
    //       .findOne({
    //         "$or": [{ openID: info.openid }, { unionID: info.unionid }]
    //       })
    //       .exec((err, doc) => {
    //         if (err) {
    //           res.send(error);
    //         } else {
    //           if (String(doc) == "null") {
    //             resolve(1)
    //           } else {
    //             resolve(2)
    //           }
    //         }
    //       });
    //   })
    // }

    //user创建或更新
    var upsert = () => {
      // if (flag == 1) {
      //   user
      //     .create({
      //       unionID: info.unionid || "",
      //       XXopenID: "",
      //       openID: info.openid,
      //       attention: false,
      //       name: "",
      //       sex: "",
      //       groups: [{ group_id: _id, name }],
      //       C_groups: []
      //     },
      //       (err, doc) => {
      //         if (err) {
      //           res.send(error);
      //         } else {
      //           res.send({
      //             error_no: 1,
      //             error_msg: 'ok'
      //           });
      //         }
      //       });
      // } else if (flag == 2) {
      user
        .updateOne({
          "$or": [{ openID: info.openid }, { unionID: info.unionid }]
        }, {
            '$push': {
              'groups': {
                group_id: _id, name
              }
            },
            $set: {
              openID: info.openid
            }
          }, (err, doc) => {
            if (err) {
              res.send(error);
            } else {
              res.send({
                error_no: 1,
                error_msg: 'ok'
              });
            }
          });
      // }
    }

    updateGroup().then(upsert)
  };

  getOpenId(code, addToGroup, res, {}, 3);
});

//解散/退出一个群组
helloworld.post('/deleteGroup', (req, res, next) => {
  var _id = req.body._id
  var name = req.body.name
  var num = req.body.num
  var code = req.body.code

  //删除成员信息
  var deleteMembers = () => {
    return new Promise(function (resolve, reject) {
      user.updateMany({}, {
        $pull: {
          "groups": {
            "group_id": _id,
            "name": name
          }
        }
      }, function (err) {
        if (err) {
          res.send(error);
        } else {
          resolve()
        }
      });
    })
  }

  //删除群主信息
  var deleteHost = () => {
    return new Promise(function (resolve, reject) {
      var update = info => {
        user.updateOne({
          openID: info.openid
        }, {
            $pull: {
              "C_groups": {
                "group_id": _id,
                "name": name
              }
            }
          }, function (err) {
            if (err) {
              res.send(error);
            } else {
              resolve()
            }
          });
      }

      getOpenId(code, update, res, {}, 3);
    })
  }

  //删除群组
  var deleteGroup = () => {
    return new Promise(function (resolve, reject) {

      groups
        .deleteOne({
          _id: _id
        }, (err) => {
          if (err) {
            res.send(error);
          } else {
            res.send({
              error_no: 1,
              error_msg: 'ok'
            });
          }
        });
    })

  };

  var quit = (info) => {
    //群组成员信息删除退出者
    var quitGroup = () => {
      return new Promise(function (resolve, reject) {
        groups
          .updateOne({ _id }, {
            $pull: {
              members: {
                openID: info.openid
              }
            }
          }, (err, doc) => {
            if (err) {
              res.send(error);
            } else {
              resolve()
            }
          })
      })
    }

    //退出者信息更新
    var updateQuiter = () => {
      return new Promise(function (resolve, reject) {
        user
          .updateOne({
            openID: info.openid
          }, {
              '$pull': {
                'groups': {
                  group_id: _id, name
                }
              }
            }, (err, doc) => {
              if (err) {
                res.send(error);
              } else {
                res.send({
                  error_no: 1,
                  error_msg: 'ok'
                });
              }
            });
      })
    }

    quitGroup().then(updateQuiter)
  }

  if (num == 1) {
    //退出群组
    getOpenId(code, quit, res, {}, 3);
  } else if (num == 2) {
    //解散群组
    deleteMembers().then(deleteHost).then(deleteGroup)
  }


});

//增加群组
helloworld.post('/addGroup', (req, res, next) => {
  var code = req.body.code;
  var name = req.body.name
  console.log(code);

  var group_id = ''

  var add = info => {
    console.log('用户信息：', info.openid, info.unionid);
    //创建群组
    function run() {
      var p = new Promise(function (resolve, reject) {
        groups
          .create({
            openID: info.openid,
            unionID: info.unionid,
            name: name,
            members: [{
              openID: info.openid,
              XXopenID: "",
              unionID: info.unionid,
              name: "",
            }]
          },
            (err, doc) => {
              if (err) {
                res.send(err);
              } else {
                group_id = doc._id
                resolve()
              }
            });
      })

      return p
    }
    // //查询user表里是否已注册
    // var step1 = () => {
    //   var p = new Promise(function (resolve, reject) {
    //     user
    //       .findOne({
    //         "$or": [{ openID: info.openid }, { unionID: info.unionid }]
    //       })
    //       .exec((err, doc) => {
    //         if (err) {
    //           res.send(error);
    //         } else {
    //           if (String(doc) == "null") {
    //             resolve(1)
    //           } else {
    //             resolve(2)
    //           }
    //         }
    //       });
    //   })

    //   return p
    // }

    //创建或更新
    var step2 = () => {
      var p = new Promise(function (resolve, reject) {

        // if (flag == 1) {
        //   user
        //     .create({
        //       unionID: info.unionid,
        //       XXopenID: "",
        //       openID: info.openid,
        //       attention: false,
        //       name: "",
        //       sex: "",
        //       groups: [],
        //       C_groups: [{ group_id, name }]
        //     },
        //       (err, doc) => {
        //         if (err) {
        //           res.send(error);
        //         } else {
        //           res.send({
        //             error_no: 1,
        //             error_msg: 'ok'
        //           });
        //         }
        //       });
        // } else if (flag == 2) {
        user
          .updateOne({
            "$or": [{ openID: info.openid }, { unionID: info.unionid }]
          }, {
              '$push': { 'C_groups': { group_id, name } },
              $set: { openID: info.openid }
            }, (err, doc) => {
              if (err) {
                res.send(error);
              } else {
                res.send({
                  error_no: 1,
                  error_msg: 'ok'
                });
              }
            });
        // }
      })

      return p
    }

    run().then(step2)
  };

  getOpenId(code, add, res, {}, 3);
});

var group_messages = require("./user_model").group_messages
//发布消息
helloworld.post('/publish', (req, res, next) => {
  var { _id,
    activity,
    name,
    host,
    time,
    place,
    comment } = req.body

  groups
    .findOne({
      _id
    }, { members: 1, _id: 0 }, { lean: true }, (err, doc) => {
      doc.members.forEach((element, index) => {
        //群发消息
        var publish = (XXopenID) => {
          return new Promise(function (resolve, reject) {
            sendTextMsg(XXopenID, activity, name, host, time, place, comment, res)
            resolve()
          })
        }

        //记录消息
        var record = () => {
          group_messages.create({
            group_id: _id,
            activity,
            name,
            host,
            time,
            place,
            comment
          }, (err, doc) => {
            if (err) {
              console.log(err)
            } else {
              console.log(doc)
            }
          })
        }

        // console.log(element.XXopenID.length, typeof element.XXopenID, element.XXopenID)

        if (element.XXopenID.length == 0) {
          //查询XXopenID
          let queryXXopenID = () => {
            return new Promise(function (resolve, reject) {
              if (element.unionID && element.unionID.length > 0) {
                user.findOne({ unionID: element.unionID }, { XXopenID: 1, name: 1, _id: 0 }, (err, doc) => {
                  if (err) {
                    console.log(err)
                  } else {
                    resolve(doc)
                  }
                })
              }
            })
          }

          //补全群组成员信息
          let complete = (doc) => {
            console.log(_id, element)
            return new Promise(function (resolve, reject) {
              groups.updateOne({
                _id,
                "members._id": element._id
              }, {
                  $set: {
                    "members.$.XXopenID": doc.XXopenID,
                    "members.$.name": doc.name
                  }
                }, (err) => {
                  if (err) {
                    console.log(err)
                  } else {
                    resolve(doc.XXopenID)
                  }
                })
            })
          }

          queryXXopenID().then(complete).then(publish).then(record)
        } else {
          publish(element.XXopenID).then(record)
        }

      });
    })
});



//进行sha1加密
function sha1(str) {
  var shasum = crypto.createHash('sha1');
  shasum.update(str);
  var str = shasum.digest('hex');
  return str;
}

function getUnionIdByXXopenID(XXopenid) {
  let queryParams = {
    access_token: token,
    openid: XXopenid,
    lang: "zh_CN"
  };

  let wxGetAccessTokenBaseUrl =
    'https://api.weixin.qq.com/cgi-bin/user/info?' + qs.stringify(queryParams);
  let options = {
    method: 'GET',
    url: wxGetAccessTokenBaseUrl
  };
  return new Promise((resolve, reject) => {
    request(options, function (err, res, body) {
      if (res) {
        resolve(JSON.parse(body));
      } else {
        getUnionIdByXXopenID(XXopenid)
      }
    });
  });
}

var subscribe = (req, res, result) => {
  var result = result.xml;
  var toUser = result.ToUserName; //接收方微信
  var fromUser = result.FromUserName; //发送方微信

  var XXinfo = {}

  //查询user表里是否已注册
  var check = (resFromWX) => {
    XXinfo = resFromWX
    return new Promise((resolve, reject) => {
      user
        .findOne({
          unionID: resFromWX["unionid"]
        })
        .exec((err, doc) => {
          if (err) {
            res.send('');
            console.log(err)
            return
          } else {
            if (String(doc) == "null") {
              resolve(1)
            } else {
              resolve(2)
            }
          }
        });
    });
  }

  //创建或更新
  var upsert = (flag) => {
    return new Promise(function (resolve, reject) {

      if (flag == 1) {
        user
          .create({
            unionID: XXinfo["unionid"],
            XXopenID: fromUser,
            openID: "",
            attention: true,
            name: XXinfo["nickname"],
            sex: XXinfo["sex"],
            groups: [],
            C_groups: []
          },
            (err, doc) => {
              if (err) {
                res.send('');
                console.log(err)
                return
              } else {
                resolve()
              }
            });
      } else if (flag == 2) {
        user
          .updateOne({ "unionID": XXinfo["unionid"] }, {
            '$set': {
              XXopenID: fromUser,
              attention: true,
              name: XXinfo["nickname"],
              sex: XXinfo["sex"],
            }
          }, {}, (err, doc) => {
            if (err) {
              res.send('');
              console.log(err)
              return
            } else {
              resolve()
            }
          });
      }
    })
  }

  var send = () => {
    res.send(
      '<xml><ToUserName><![CDATA[' +
      fromUser +
      ']]></ToUserName>' +
      '<FromUserName><![CDATA[' +
      toUser +
      ']]></FromUserName>' +
      '<CreateTime>' +
      new Date().getTime() +
      '</CreateTime>' +
      '<MsgType><![CDATA[text]]></MsgType>' +
      '<Content><![CDATA[' +
      '欢迎关注 OursparkMinelab 服务号，本服务号用于发送待办事项提醒，衷心希望您能喜欢此服务！\n\n' +
      '加入群组方法：\n' +
      '1、打开ourspark小程序 \n' +
      '2、点击“我的”标签\n' +
      '3、点击“我参加的群组”\n' +
      '4、点击“扫码加入消息群组”，扫描想加入的群组的二维码即可\n' +
      '5、加入群组后，群组创建者发送的消息可以在本服务号里看到\n\n' +
      '创建群组方法：\n' +
      '1、打开ourspark小程序 \n' +
      '2、点击“我的”标签\n' +
      '3、点击“我创建的群组”\n' +
      '4、点击“新建消息群组” \n' +
      '5、新建完成后，将群组二维码分享给他人，他人扫码加入群组后就可以在本服务号收到你在ourspark小程序中发布的消息提醒了 \n' +
      '\n----------------------\n' +
      '如对此服务号或者ourspark小程序有反馈意见或建议，请在此服务号发送消息即可~ \n' +
      ']]></Content></xml>'
    );
    return
  }

  getUnionIdByXXopenID(fromUser).then(check).then(upsert).then(send)
};

var unsubscribe = (req, res, result) => {
  var openID = result.xml.FromUserName; //发送方微信
  res.send('');

  // console.log(openID + "    aswiehvrbvi")

  user.update(
    {
      "XXopenID": openID
    },
    {
      '$set': {
        "attention": false
      }
    }, {},
    (error, doc) => {
      // console.log("jieguo")
      if (error) {
        console.log(error);
      } else {
        console.log(doc);
      }
    }
  );
};

var sendTextMsg = (XXopenID, activity, name, host, time, place, comment, res) => {

  var requestData = {
    touser: XXopenID,
    template_id: '4V-1AKRgp6Bwd0dF1d9IsWkxUY-QA9Vl_e_9hqa2nQk',
    data: {
      first: {
        value: activity,
        color: '#ff0000'
      },
      keyword1: {
        value: name,
        color: '#173177'
      },
      keyword2: {
        value: host,
        color: '#173177'
      },
      keyword3: {
        value: time,
        color: '#173177'
      },
      keyword4: {
        value: place,
        color: '#173177'
      },
      remark: {
        value: comment,
        color: '#173177'
      }
    }
  };
  // console.log('回复token:  ' + token);
  request(
    {
      url:
        'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' +
        token,
      method: 'POST',
      json: true,
      headers: {
        'content-type': 'application/json'
      },
      body: requestData
    },
    function (error, response, third) {
      if (!error && response.statusCode == 200) {
        console.log('发送完毕', '|| third: ', third);
        res.send({
          error_no: 1,
          error_msg: 'ok'
        })
      }
    }
  );



};

var feedback_messages = require("./user_model").feedback_messages
var feed_back = (req, res, result) => {
  var xml = result.xml;
  var FromUserName = xml.FromUserName;//发送方微信
  var ToUserName = xml.ToUserName; //接收方微信
  var content = xml.Content;

  res.send(
    '<xml><ToUserName><![CDATA[' +
    FromUserName +
    ']]></ToUserName>' +
    '<FromUserName><![CDATA[' +
    ToUserName +
    ']]></FromUserName>' +
    '<CreateTime>' +
    new Date().getTime() +
    '</CreateTime>' +
    '<MsgType><![CDATA[text]]></MsgType>' +
    '<Content><![CDATA[' +
    '感谢留言反馈！我们会及时查看并修复相应问题！' +
    ']]></Content></xml>'
  );

  var feed = (resFromWX) => {
    feedback_messages.create({
      openid: FromUserName,
      unionid: resFromWX["unionid"],
      content: content
    },
      (err, doc) => {
        if (err) {
          console.log(err)
        }
      });
  }

  getUnionIdByXXopenID(FromUserName).then(feed)

}

var templateFinish = (req, res, result) => {
  var xml = result.xml;
  var status = xml.Status;

  if (status == 'success') {
    console.log('success');
  } else if (status == 'failed:user block') {
    console.log('failed:user block');
  } else if (status == 'failed: system failed') {
    console.log('failed: system failed');
  } else {
    console.log('something wrong!');
  }
};

//返回图片
helloworld.get('/image', (req, res, next) => {
  var url = req.query.url;

  res.writeHead(200, { 'Content-Type': 'image/gif' });
  res.end(fs.readFileSync(__dirname + "/../../../../helloworld/static/images/" + url ));

});

module.exports = helloworld;
